package com.abel.quiz.socket;/**
 * Created by abel.lin on 2017/11/7.
 */

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import javax.servlet.http.HttpSession;
import java.util.Map;

/**
 * @author abel.lin
 * @date_time 2017/11/7 14:54
 * @description
 */
public class WebSocketHandshakeInterceptor implements HandshakeInterceptor {
    /**
     * 建立WebSocket连接、握手前的处理方
     * 从HttpSession读取当前用户的用户ID（OpenID或管理员的名字），写入attributes
     *
     * @param request Http请求对象
     * @param response Http响应对象
     * @param wsHandler WebSocketHandler实现类的实例，这里是SystemWebSocketHandler类
     * @param attributes 握手生成的WebSocketSession对象的属性
     * @return 是否成功
     * @throws Exception 接口方法声明的异常
     */
    public boolean beforeHandshake(ServerHttpRequest request,ServerHttpResponse response, WebSocketHandler wsHandler,
                                   Map<String, Object> attributes) throws Exception {
        System.out.println("Websocket:用户[ID:"+ ((ServletServerHttpRequest) request).getServletRequest()
                .getSession(false).getAttribute("uid") + "]已经建立连接");
        if (request instanceof ServletServerHttpRequest) {
            ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) request;
            HttpSession session = servletRequest.getServletRequest().getSession(false);
            // 标记用户
            Long uid = Long.valueOf(session.getAttribute("uid").toString());
            if (uid != null) {
                attributes.put("uid", uid);
            } else {
                return false;
            }
        }
        return true;
    }
    public void afterHandshake(ServerHttpRequest request,ServerHttpResponse response, WebSocketHandler wsHandler,
                               Exception exception) {
    }
}
